// 防抖函数
function debounce(func, delay = 500, immediate, resultCallback) {
    let timer = null;
    let isInvoke = false;

    const _debounce = function (...args) {
        return new Promise((resolve, reject) => {
            if (timer) clearTimeout(timer);

            if (immediate &&!isInvoke) {
                try {
                    const result = func.apply(this, args);
                    if (resultCallback) resultCallback(result);
                    resolve(result);
                } catch (e) {
                    reject(e);
                }
                isInvoke = true;
            } else {
                timer = setTimeout(() => {
                    try {
                        const result = func.apply(this, args);
                        if (resultCallback) resultCallback(result);
                        resolve(result);
                    } catch (e) {
                        reject(e);
                    }
                    isInvoke = false;
                    timer = null;
                }, delay);
            }
        });
    };

    _debounce.cancel = function () {
        if (timer) clearTimeout(timer);
        isInvoke = false;
        timer = null;
    };

    return _debounce;
}

// 节流函数
function throttle(func, interval, options = { leading: false, trailing: true }) {
    let timer = null;
    let lastTime = 0;
    const { leading, trailing } = options;

    const _throttle = function (...args) {
        const nowTime = Date.now();
        if (!lastTime &&!leading) lastTime = nowTime;
        const remainTime = interval - (nowTime - lastTime);
        if (remainTime <= 0) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            lastTime = nowTime;
            func.apply(this, args);
        }
        if (trailing &&!timer) {
            timer = setTimeout(() => {
                lastTime =!leading? 0 : Date.now();
                timer = null;
                func.apply(this, args);
            }, remainTime);
        }
    };

    _throttle.cancel = function () {
        if (timer) clearTimeout(timer);
        timer = null;
        lastTime = 0;
    };

    return _throttle;
}

// 驼峰转换下划线
function toLine(name) {
    return name.replace(/([A-Z])/g, '_$1').toLowerCase();
}

export { toLine, throttle, debounce }